from rest_framework import serializers
from course import models

class CategorySer(serializers.ModelSerializer):
    class Meta:
        model = models.Category
        fields = ["id","name"]

class CategorySerializer(serializers.ModelSerializer):
    #嵌套查询
    children= CategorySer(many=True)#many=True表示一对多
    class Meta:
        model = models.Category
        fields = '__all__'

#使用递归和嵌套序列化来展示所有层级的数据 通过children属性来设置子类
class CateSerializer(serializers.ModelSerializer):
    children = serializers.SerializerMethodField()#关系序列化自定义的函数
    def get_children(self,obj):#当前类的实例
        #判断当前obj是否有子类
        if obj.children.all().exists():
            return CategorySerializer(obj.children.all(),many=True).data
        else:
            return []
    class Meta:
        model = models.Category
        fields = '__all__'